﻿using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine;

public class NetDataBuffer {
    private byte[] buffer;
    private int offset;
    private int length;
    public bool error;

    public static int BUFFER_LENGTH = 40960;

    public NetDataBuffer()
    {
        buffer = new byte[BUFFER_LENGTH];
    }

    /**
	 * 追尾一个字符串
	 * @param bytes
	 */
    public void append(byte[] bytes)
    {
        Array.Copy(bytes, 0, buffer, offset, bytes.Length);

        offset += bytes.Length;
        length += bytes.Length;
    }

    public void append(byte[] bytes, int length)
    {
        Array.Copy(bytes, 0, buffer, offset, length);

        offset += length;
        this.length += length;
    }

    /**
	 * 获取一个消息
	 * @return
	 */
    public NetData pick()
    {
        error = false;

        if (length < 4)
            return null;

        NetData net_data = new NetData();
        int read_length = net_data.fill(buffer);

        if (read_length <= 0 || read_length >= 40960)
        {
            error = true;
            return null;
        }

        int reset_length = length - read_length;

        if (reset_length < 0 || reset_length >= BUFFER_LENGTH)
        {
            error = true;
            return null;
        }

        Array.Copy(buffer, read_length, buffer, 0, reset_length);

        length -= read_length;
        offset -= read_length;

        return net_data;
    }
}
